package org.gd.httprequests;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.net.Proxy.Type.*;

/**
 * @author Gorhover
 */
public class StreamApp {

    public static Proxy proxy() {
        return new Proxy(HTTP, new InetSocketAddress("10.1.100.25", 8080));
    }

    public static String auth() throws IOException {
        String auth = new BASE64Encoder().encode("dn261089gdp:an470040cfg".getBytes());
        return "Basic " + auth;
    }

    public static void main(String ... args) {
        try {
            for(String site: sitesList()) {
                URL url = new URL(site);
                URLConnection urlConnection = url.openConnection(proxy());
                urlConnection.setRequestProperty("Proxy-Connection", "Keep-Alive");
                urlConnection.setRequestProperty("Proxy-Authorization", auth());
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i = 0;
                for(;;i++) {
                    int b = inputStream.read();
                    if(b == -1) {
                        break;
                    }
                    byteArrayOutputStream.write(b);
                }
                String html = byteArrayOutputStream.toString();

                Pattern pattern = Pattern.compile(
                        "(" +
                                "[0-9] [0-9]{3} [0-9]{3} [0-9]{3}" +
                                "|" +
                                "[0-9]-[0-9]{3}-[0-9]{2}-[0-9]{2}-[0-9]{2}" +
                                "|" +
                                "[+]38 (044) 590-37-37" +
                        ")");
                Matcher matcher = pattern.matcher(html);

                while (matcher.find()) {
                    System.out.println(site + ": " + matcher.group());
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }

    private static List<String> sitesList() {
        List<String> sitesList = new ArrayList<String>();
        sitesList.add("http://deltabank.com.ua/personal/internet-banking/");
        sitesList.add("http://www.alfabank.com.ua/");
        return sitesList;
    }
}
